<template>
  <v-layout title="添加/修改买号纪录">
    <el-row type="flex" justify="center" class="comfirm">
      <el-col :lg="14" :md="14" :sm="28" :xs="24">
        <v-form
          :form-title="formTitle1"
          :form-data="formData"
          label-width="100px"
          @focus="focus"
        >
          <template
            slot="uploadImg"
            slot-scope="scope"
          >
            <el-form-item :label="scope.info.cn">
              <el-upload
                ref="upload"
                :on-preview="handlePreview"
                :file-list="fileList"
                :auto-upload="false"
                class="upload-demo"
                action="123">
                <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">
                  上传到服务器
                </el-button>
              </el-upload>
            </el-form-item>
          </template>

        </v-form>

        <record-table
          :table-title="paymentTitle"
          :table-data="paymentData"
          title="付款记录"
          @addNew="addPayment"
          @edit="editPayment"
          @del="delPayment"
        />

        <v-form
          :form-title="formTitle2"
          :form-data="formData"
          class="mt15"
          label-width="100px"
        />

        <el-card class="mb15" body-style="padding-top:10px">
          <div slot="header" class="bold">
            包含公众号
          </div>
          <v-tableBtns
            :show-export="false"
            :show-create="true"
            box-style="padding-bottom:10px"
            @addNew="addNewTencent"
          />
          <v-table
            :table-title="tencentTitle"
            :table-data="tencentData"
            :readable="true"
            :editable="false"
            :deletable="true"
            btn-class="btn"
            @edit="editTencent"
            @del="delTencent"
            @read="readTencent"
          />
        </el-card>

        <record-table
          :table-title="invoiceTitle"
          :table-data="invoiceData"
          title="发票信息"
          @addNew="addInvoice"
          @edit="editInvoice"
          @del="delInvoice"
        />
        <el-form label-width="120px" size="small" class="mt15 confirm">
          <el-form-item label="发票总金额">
            <el-input :disabled="true" v-model="totalMoney"/>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="formData.notes" type="textarea"/>
          </el-form-item>
        </el-form>

        <v-resetConfirmBtn
          @reset="reset"
          @confirm="submit"
        />

        <!--<el-row type="flex" justify="end" class="pdt15">-->
        <!--<el-button type="primary" @click="reset">撤销修改</el-button>-->
        <!--<el-button type="primary" @click="submit">确定</el-button>-->
        <!--</el-row>-->
      </el-col>
    </el-row>

    <!--修改付款记录等-->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      width="30%"
    >
      <v-form
        :form-title="dialogFormTitle"
        :form-data="dialogFormData"
      />
      <v-resetConfirmBtn
        @reset="resetDialog"
        @confirm="submitDialog"
      />
    </el-dialog>

    <!--添加公众号-->
    <el-dialog
      :visible.sync="tencentDialogVisible"
      width="30%"
      title="添加公众号"
    >
      <el-form label-width="120px" size="mini">
        <el-form-item label="选择公众号">
          <el-select
            v-model="dialogFormData.mpsname"
            filterable
            @change="tencentChange"
          >
            <el-option
              v-for="(item,index) in tencentList"
              :label="item.label"
              :value="item.label"
              :key="item.value"/>
          </el-select>
          <el-button type="primary" @click="createTencent">新增公众号</el-button>
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="dialogFormData.money"/>
        </el-form-item>
        <el-form-item label="生效时间">
          <el-date-picker
            v-model="dialogFormData.start_time"
            :default-value="dialogFormData.start_time"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
      </el-form>

      <v-resetConfirmBtn
        @reset="resetDialog"
        @confirm="submitDialog"
      />
    </el-dialog>

    <!--选择合同-->
    <el-dialog
      :visible.sync="showContractDialog"
      width="60%"
      title="请选择合同"
    >
      <contract
        @use="useContract"
      />
    </el-dialog>

  </v-layout>
</template>

<script>
  import contract from '../components/contractSelect'
  import recordTable from '../../components/record_table'

  export default {
    components: {contract, recordTable},
    data() {
      return {
        buy_fans_record_id: '',

        dialogTitle: '',
        dialogVisible: false,
        tencentDialogVisible: false,
        showContractDialog: false,
        showModel: false,
        previewUrl: '',
        fileList: [],

        // 第一部分表单标题
        formTitle1: [
          {
            cn: '合同编号',
            en: 'ct_number',
            // disabled:true,
            focus: true
          },
          {
            cn: '合同附件',
            en: 'appendices',
            disabled: true
          },
          {
            cn: '对方单位名称',
            en: 'opposing_party_unit',
            disabled: true
          },
          {
            cn: '采购内容',
            en: 'procurement_contents',
            type: 'textarea',
            disabled: true
          },
          {
            cn: '合同金额',
            en: 'money'
            // disabled: true
          },
          {
            cn: '税点',
            en: 'tax_point'
          },
          {
            cn: '已付款金额',
            en: 'real_pay',
            disabled: true
          },
          {
            cn: '付款状态',
            en: 'payment_status',
            type: 'select',
            disabled: true,
            list: [
              {
                label: '未收款',
                value: '1'
              },
              {
                label: '终止',
                value: 'TERMINATED'
              },
              {
                label: '已完成',
                value: 'COMPLETED'
              }
            ]
          }

        ],
        // 第二部分表单标题
        formTitle2: [
          {
            cn: '签订日期',
            en: 'date_of_signing',
            disabled: true
          },
          {
            cn: '合同状态',
            en: 'contract_status',
            type: 'select',
            disabled: true,
            list: [
              {
                label: '签约',
                value: '1'
              },
              {
                label: '执行中',
                value: '2'
              },
              {
                label: '完毕',
                value: 'COMPLETED'
              },
              {
                label: '意外终止',
                value: '4'
              }
            ]
          },
          {
            cn: '签订人',
            en: 'signing_people',
            disabled: true
          }
        ],
        formData: {},

        // 付款记录
        paymentTitle: [
          {
            cn: 'id',
            en: 'id'
          },
          {
            cn: '付款银行',
            en: 'bank'
          },
          {
            cn: '付款金额',
            en: 'money'
          },
          {
            cn: '付款时间',
            en: 'create_date'
          },
          // {
          //   cn: '修改人',
          //   en: 'name'
          // },
          // {
          //   cn: '最后修改时间',
          //   en: 'update_date',
          // }
        ],
        paymentData: [],
        originData: {},
        paymentFormTitle: [
          {
            cn: '付款银行',
            en: 'bank'
          },
          {
            cn: '付款金额',
            en: 'money'
          },
          {
            cn: '付款时间',
            en: 'create_date',
            type: 'time'
          }
        ],

        dialogFormTitle: [],
        dialogFormData: {},

        // 公众号
        tencentTitle: [
          {
            cn: '公众号id',
            en: 'mpsid'
          },
          {
            cn: '公众号',
            en: 'mpsname'
          },
          {
            cn: '金额',
            en: 'money'
          },
          {
            cn: '不含税原值',
            en: 'balance',
            disabled: true
          },
          {
            cn: '成本计算时间',
            en: 'cycle'
          },
          {
            cn: '每月摊销',
            en: 'per_month_cost'
          },
          {
            cn: '生效时间',
            en: 'start_time'
          }
        ],
        tencentData: [],
        tencentFormTitle: [
          {
            cn: '选择公众号',
            en: 'mp_id'
          }
        ],
        tencentList: [], // 公众号列表
        selectedTencent: '',
        tencentFormData: {},

        // 发票信息
        invoiceTitle: [
          {
            cn: '开票号码',
            en: 'invoice_code'
          },
          {
            cn: '对方公司',
            en: 'company'
          },
          {
            cn: '含税金额',
            en: 'money'
          },
          {
            cn: '开票时间',
            en: 'create_date'
          },
          // {
          //   cn: '修改人',
          //   en: 'name'
          // }
        ],
        invoiceData: [],
        invoiceFormTitle: [
          {
            cn: '开票号码',
            en: 'invoice_code'
          },
          {
            cn: '对方公司',
            en: 'company'
          },
          {
            cn: '含税金额',
            en: 'money'
          },
          {
            cn: '开票时间',
            en: 'create_date',
            type: 'time'
          }
        ],
        messages: [],
        url: '',
        modifyData: '',

        isEdit: false,   //是否是修改表格
        index: null,    // 是修改时的序号
      }
    },
    computed: {
      totalMoney() {
        let total = 0
        this.invoiceData.forEach(item => {
          total += +(item.money || 0)
        })
        return total
      },
      title() {
        if (this.$route.query.id) {
          return '创建合同'
        }
      },
      orderWarning() {
        return !this.formData.ct_number
      },
      payedMoney() {
        let total = 0
        this.paymentData.forEach(item => {
          total += +(item.money || 0)
        })
        if (!total) {
          this.formData.real_pay = total;
        }
        return total
      },
    },
    watch: {
      payedMoney(val) {
        this.$set(this.formData, 'real_pay', val)
      }
    },

    activated() {
      localStorage.removeItem('paymentData')
      localStorage.removeItem('invoiceData')
      localStorage.removeItem('tencentData')

      this.buy_fans_record_id = this.$route.query.id
      if (this.buy_fans_record_id) {
        this.getBuyAccountDetail()
      } else {
        this.formData = {};
        this.paymentData = []
        this.tencentData = []
        this.invoiceData = []
      }
    },
    mounted() {
      this.getTencentList()
    },
    methods: {
      // 获取买号记录详情
      getBuyAccountDetail() {
        const data = {id: this.buy_fans_record_id}
        this.$get('action/BuympsRecord/qryOp', data)
          .then(res => {
            this.tencentData = res.data.Buympsmpinfo.map(item => {
              item.cycle = '60'
              item.per_month_cost = (item.balance / 60).toFixed(2)
              return item
            }) || []// 买号公众号记录
            this.formData = {...res.data.BuympsRecord, ...this.formData} || {}// 买量合同
            this.invoiceData = res.data.Buympsinvoiceinfo || []// 买号发票信息
            this.paymentData = res.data.Buympspayrecord || []// 买号打款
          })
      },

      // 选用该条合同详情
      useContract(val) {
        this.showContractDialog = false
        this.formData = val.row
      },
      focus(val, name) {
        console.log(val)
        this.showContractDialog = true
      },

      submitUpload() {
        this.$refs.upload.submit()
      },
      handlePreview(file) {
        console.log(file)
        this.showModel = true
        this.previewUrl = file.url
      },
      // 添加付款记录
      addPayment(val) {
        this.dialogTitle = '添加付款记录'
        this.url = 'action/Buympspayrecord/save'
        this.key = 'paymentData'
        // this.modifyData = 'paymentData';
        this.showDialog(this.paymentFormTitle)
      },
      // 修改付款记录
      editPayment(val) {
        this.dialogTitle = '修改付款记录';
        this.url = 'action/Buympspayrecord/save';
        this.key = 'paymentData'
        // this.modifyData = 'paymentData';
        this.showDialog(this.paymentFormTitle, val.row)
        this.isEdit = true
        this.index = val.$index
      },
      delPayment(val) {
        if (this.buy_fans_record_id) {
        const data = {
          id: val.row.id,
          buy_fans_record_id: this.buy_fans_record_id
        }
        this.$post('action/Buympspayrecord/del', data)
          .then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getBuyAccountDetail()
          })
      } else {
        this.paymentData.splice(val.$index, 1)
      }
      },
      // 发票信息
      addInvoice(val) {
        this.dialogTitle = '添加发票信息'
        this.url = 'action/Buympsinvoiceinfo/save'
        this.key = 'invoiceData'
        // this.modifyData = 'invoiceData';
        this.showDialog(this.invoiceFormTitle)
      },
      editInvoice(val) {
        this.dialogTitle = '修改发票信息'
        this.url = 'action/Buympsinvoiceinfo/save'
        this.key = 'invoiceData'
        // this.modifyData = 'invoiceData';
        this.showDialog(this.invoiceFormTitle, val.row)
        this.isEdit = true
        this.index = val.$index
      },
      delInvoice(val) {
        if (this.buy_fans_record_id) {
          const data = {
            id: val.row.id,
            buy_fans_record_id: this.buy_fans_record_id
          }
          this.$post('action/Buympsinvoiceinfo/del', data)
            .then(res => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
            })
          this.getBuyAccountDetail()
        } else {
          this.invoiceData.splice(val.$index, 1)
        }
      },
      // 新增/修改对话框
      showDialog(title, val) {
        this.dialogFormTitle = title
        this.originData = val || {}
        this.dialogVisible = true
        this.dialogFormData = this.$deepClone(this.originData)
      },
      resetDialog() {
        this.dialogFormData = this.$deepClone(this.originData)
      },
      submitDialog() {
        // this.dialogFormData.id = this.dialogFormData.id ? '' + this.dialogFormData.id : ''

        // this.dialogFormData.id = this.dialogFormData.id ? '' + this.dialogFormData.id : ''
        let status;
        if (this.key !== 'tencentData') {
          status = this.dialogFormTitle.every(item=>{
            return this.dialogFormData[item.en]||this.dialogFormData[item.en]==0
          })
        }else{  //如果是公众号详情, 就计算不含税原值等
          const money = this.dialogFormData.money;
          const point = this.dialogFormData.tax_point || 0;
          this.dialogFormData.balance = (money / (1 + point)).toFixed(2)
          this.dialogFormData.per_month_cost = (this.dialogFormData.balance / 60).toFixed(2)
          this.dialogFormData.cycle = 60;
          const data = this.dialogFormData;
          status = data.money>=0&&data.mpsname&&data.start_time
        }
        if (!status) {
          return this.$message({
            message: '请填写完整',
            type: 'error'
          })
        }
        const data = {
          ...this.dialogFormData,
          buy_fans_record_id: this.buy_fans_record_id,
          tax_point: this.formData.tax_point || 0
        }
        if (this.buy_fans_record_id) {
          this.$post(this.url, data)
            .then(res => {
              this.dialogFormData = {}
              this.dialogFormTitle = null
              this.url = ''
              this.getBuyAccountDetail()
            })
        } else {
          let lists = localStorage.getItem(this.key) ? JSON.parse(localStorage.getItem(this.key)) : [];
          if (this.isEdit) {  //如果是修改
            this.$set(this[this.key], this.index, data)
          } else { // 如果是新增
            lists.push(data)
            this[this.key].push({...data,});
          }
          localStorage.setItem(this.key, JSON.stringify(lists))
          this.isEdit = false
          this.index = null
        }
        this.tencentDialogVisible = false
        this.dialogVisible = false
      },

      // 获取公众号列表
      getTencentList() {
        this.$get('action/WechatNumber/tree')
          .then(res => {
            const list = []
            if (res.data.WechatTree) {
              res.data.WechatTree.forEach(item => {
                list.push({
                  label: item.name,
                  value: item.id
                })
              })
            }
            this.tencentList = list
          })
      },
      delTencent(val) {
        if (this.buy_fans_record_id) {
        const data = {
          id: val.row.id,
          buy_fans_record_id: this.buy_fans_record_id
        }

        this.$post('action/Buympsmpinfo/del', data)
          .then(res => {
            this.$message({
              message: res.msg,
              type: 'success'
            })
            this.getBuyAccountDetail()
          })
        } else {
          this.tencentData.splice(val.$index, 1)
        }
      },
      // 查看公众号
      readTencent(val) {
        this.$router.push({
          name: 'tencent_list.tencent_create',
          query: {
            id: val.row.mpsid
          }
        })
      },
      tencentChange(val) {
        console.log(val)
        this.tencentList.forEach(item => {
          if (item.label === val) {
            return this.dialogFormData.mpsid = item.value
          }
        })
      },

      editTencent(val) {
        this.tencentDialogVisible = true
        this.url = 'action/Buympsmpinfo/save'
        this.key = 'tencentData'
        this.dialogFormData = val.row
        this.isEdit = true
        this.index = val.$index
      },
      createTencent() {
        this.$router.push({
          name: 'tencent_list.tencent_create'
        })
      },
      // 选择公众号
      addNewTencent() {
        this.tencentDialogVisible = true
        this.url = 'action/Buympsmpinfo/save'
        this.key = 'tencentData'
        // this.modifyData = 'tencentData';
        this.dialogFormData = {}
      },

      reset() {
        this.getBuyAccountDetail()
      },
      // 获取买号记录id
      getAccountRecordId() {
        return new Promise((resolve, reject) => {
          this.$get('action/BuympsRecord/save')
            .then(res => {
              this.buy_fans_record_id = res.data;
              resolve(res)
            })
            .catch(err => {
              reject(err)
            })
        })
      },

      submitTable(url, data) {
        if (data && data instanceof Array && data.length > 0) {
          data.forEach(item => {
            item.buy_fans_record_id = this.buy_fans_record_id
            item.tax_point = this.formData.tax_point || 0
            this.$post(url, item)
              .then(res => {

              })
          })
        }
      },

      submit() {
        if (this.orderWarning) {
          this.$alert('请选择合同', '提示', {
            confirmButtonText: '确定'
          })
        } else {
          if (this.buy_fans_record_id) {
            this.submit2()
          } else {
            this.getAccountRecordId()
              .then(res => {
                const data1 = localStorage.getItem('paymentData') ? JSON.parse(localStorage.getItem('paymentData')) : []
                const data2 = localStorage.getItem('invoiceData') ? JSON.parse(localStorage.getItem('invoiceData')) : []
                const data3 = localStorage.getItem('tencentData') ? JSON.parse(localStorage.getItem('tencentData')) : []
                this.submitTable('action/Buympspayrecord/save', data1);
                this.submitTable('action/Buympsinvoiceinfo/save', data2);
                this.submitTable('action/Buympsmpinfo/save', data3);
                this.submit2()
              })

          }
        }
      },
      submit2() {
        const data = {
          id: +this.buy_fans_record_id,
          ...this.formData,
          money: this.formData.money || 0,
          tax_point: this.formData.tax_point || 0
        }
        this.$post('action/BuympsRecord/update', data)
          .then(res => {
            new Promise((resolve, reject) => {
              this.$message({
                message: res.msg,
                type: 'success'
              })
              resolve()
            }).then(_ => this.$router.go(-1))
          })
      }

    }
  }
</script>

<style scoped>

</style>
